/*
https://leetcode.cn/problems/moving-stones-until-consecutive-ii/solution/jie-ti-si-lu-by-owenzzz/
 */
import java.util.Arrays;

public class Solution1040 {
    public int[] numMovesStonesII(int[] stones) {
        Arrays.sort(stones);
        int n=stones.length;
        int max=Math.max(stones[n-1]-stones[1],stones[n-2]-stones[0])+2-n;
        int j=0;
        int min=max;
        for (int i=0;i<n;i++){
            while (j+1<n && stones[j+1]-stones[i]+1<=n){
                j++;
            }
            int cost=n-(j-i+1);
            if (j-i+1==n-1 && stones[j]-stones[i]+1==n-1){
                cost=2;
            }
            min=Math.min(min,cost);
        }
        return new int[]{min,max};
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new Solution1040().numMovesStonesII(new int[]{1, 2, 3, 4, 6})));
    }
}
